<template>
  <div>
    <!-- 三级分类结构 -->
    <Category :scene="scene"></Category>
    <!-- 卡片结构 -->
    <el-card style="margin: 10px 0px">
      <!-- 场景0 -->
      <div v-show="scene == 0">
        <!-- 添加SPU按钮 -->
        <el-button
          type="primary"
          size="default"
          icon="Plus"
          :disabled="categoryStore.c3Id ? false : true"
          @click="addSpu"
        >
          添加SPU
        </el-button>
        <!-- 表格 -->
        <el-table style="margin: 10px 0px" border :data="spuDataArr">
          <el-table-column
            label="序号"
            type="index"
            align="center"
            width="80px"
          ></el-table-column>
          <el-table-column label="SPU名称" prop="spuName"></el-table-column>
          <el-table-column
            label="SPU描述"
            prop="description"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column label="SPU操作">
            <!-- row为每一个SpuData对象 -->
            <template #="{ row, $index }">
              <el-button
                type="primary"
                size="small"
                icon="Plus"
                title="添加SKU"
                @click="addSku(row)"
              ></el-button>
              <el-button
                type="primary"
                size="small"
                icon="Edit"
                title="修改SPU"
                @click="updateSpu(row)"
              ></el-button>
              <el-button
                type="primary"
                size="small"
                icon="View"
                title="查看SKU列表"
                @click="findSku(row)"
              ></el-button>
              <el-popconfirm
                title="确定删除吗?"
                width="200px"
                @confirm="deleteSpu(row)"
              >
                <template #reference>
                  <el-button
                    type="primary"
                    size="small"
                    icon="Delete"
                    title="删除SPU"
                  ></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <el-pagination
          v-model:current-page="pageNo"
          v-model:page-size="pageSize"
          :page-sizes="[3, 5, 7, 9]"
          :background="true"
          layout="prev, pager, next, jumper,->,sizes,total"
          :total="total"
          @current-change="getHasSpu"
          @size-change="changeSize"
        />
      </div>
      <!-- 场景1 -->
      <SpuForm
        v-show="scene == 1"
        @changeScene="changeScene"
        ref="spu"
      ></SpuForm>
      <!-- 场景2 -->
      <SkuForm
        v-show="scene == 2"
        @changeScene="changeScene"
        ref="sku"
      ></SkuForm>
      <!-- dialog对话框：展示已有的SKU数据 -->
      <el-dialog v-model="show" title="SKU列表">
        <el-table border :data="skuArr">
          <el-table-column label="SKU名字" prop="skuName"></el-table-column>
          <el-table-column label="SKU价格" prop="price"></el-table-column>
          <el-table-column label="SKU重量" prop="weight"></el-table-column>
          <el-table-column label="SKU图片">
            <template #="{ row, $index }">
              <img
                :src="row.skuDefaultImg"
                alt=""
                style="width: 100px; height: 100px"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onBeforeUnmount } from 'vue'
import useCategoryStore from '@/store/modules/category'
import { reqHasSpu, reqSkuList, reqRemoveSpu } from '@/api/product/spu'
import type {
  HasSpuResponseData,
  SpuData,
  SkuInfoData,
  SkuData,
} from '@/api/product/spu/type'
import SpuForm from './spuForm.vue'
import SkuForm from './skuForm.vue'
import { ElMessage } from 'element-plus'

//场景的数据（0：显示已有SPU 1：添加或修改已有SPU 2：添加SKU）
let scene = ref<number>(0)
//页码 每页条数
let pageNo = ref<number>(1)
let pageSize = ref<number>(3)
//分类仓库
let categoryStore = useCategoryStore()
//SPU数组 SPU数组长度
let spuDataArr = ref<SpuData[]>([])
let total = ref<number>(0)
//获取子组件的组件实例
let spu = ref<any>()
let sku = ref<any>()
//存储全部SKU数据
let skuArr = ref<SkuData[]>([])
//控制对话框的显示和隐藏
let show = ref<boolean>(false)

//监听三级分类Id的变化
watch(
  () => categoryStore.c3Id,
  () => {
    //三级分类Id发生变化，清空上一次查询到的SPU数组
    spuDataArr.value = []
    //没有三级分类直接返回
    if (!categoryStore.c3Id) return
    //发送请求获得SPU数组
    getHasSpu()
  },
)

//发送请求获得（查询）SPU数组
const getHasSpu = async (pager = 1) => {
  //修改当前页码
  pageNo.value = pager
  //发送请求获得SPU数组
  let result: HasSpuResponseData = await reqHasSpu(
    pageNo.value,
    pageSize.value,
    categoryStore.c3Id,
  )
  if (result.code == 200) {
    //获得SPU数组
    spuDataArr.value = result.data.records
    //SPU数组的长度
    total.value = result.data.total
  }
}
//分页器页码大小发生变化的回调
const changeSize = () => {
  getHasSpu()
}
//子组件SpuForm绑定自定义事件的回调：收到子组件传递过来的数据
const changeScene = (obj: any) => {
  //num为0，切换为场景0
  scene.value = obj.flag
  //重新获取所有SPU数据：更新留在当前页，添加留在第一页
  if (obj.params == 'update') {
    getHasSpu(pageNo.value)
  } else {
    getHasSpu()
  }
}
//点击修改SPU按钮的回调
const updateSpu = (row: SpuData) => {
  //切换为场景1
  scene.value = 1
  //调用子组件中暴露的方法：获取完整已有的SPU数据（目前不完整）
  spu.value.initHasSpuData(row)
}
//点击添加Spu按钮的回调
const addSpu = () => {
  //切换为场景1
  scene.value = 1
  //调用子组件暴露的方法：初始化SPU数据
  spu.value.initAddSpu(categoryStore.c3Id)
}
//添加SKU按钮的回调
const addSku = (row: SpuData) => {
  //切换为场景2
  scene.value = 2
  //调用子组件的方法初始化添加SKU数据
  sku.value.initSkuData(categoryStore.c1Id, categoryStore.c2Id, row)
}
//点击查看所有的SKU列表
const findSku = async (row: SpuData) => {
  //发送请求获取所有SKU列表
  let result: SkuInfoData = await reqSkuList(row.id as number)
  if (result.code == 200) {
    //存储SKU列表
    skuArr.value = result.data
    //展示对话框
    show.value = true
  }
}
//点击确定删除SPU的回调
const deleteSpu = async (row: SpuData) => {
  //发送请求删除某个SPU
  let result: any = await reqRemoveSpu(row.id as number)
  if (result.code == 200) {
    //消息提示
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    //重新获取SPU数据
    getHasSpu(spuDataArr.value.length > 1 ? pageNo.value : pageNo.value - 1)
  } else {
    //消息提示
    ElMessage({
      type: 'error',
      message: '删除失败',
    })
  }
}
//路由组件卸载前的钩子：清空分类仓库的数据
onBeforeUnmount(() => {
  categoryStore.$reset()
})
</script>

<style scoped></style>
